<?php
if (!empty($_POST['formToken']) && checkToken('frontend', $_POST['formToken'], false)) {
    switch ($_POST['action']) {
        case 'create':
            // try {
            //     require_once 'includes/createsend/csrest_subscribers.php';
            //     $wrap = new CS_REST_Subscribers('', '060d24d9003a77b06b95e7c47691975b'); //!!!! UPDATE CREATESEND LIST CODE !!!!!
            //     $cs_result = $wrap->add(array(
            //       'EmailAddress' => $_POST['email'],
            //       'Name' => $_POST['gname'].' '.$_POST['surname'],
            //       'CustomFields' => array(),
            //       'Resubscribe' => 'true',
            //     ));
            // } catch (Exception $e) {
            // }
            //验证手机短信码是否正确
            $smscode = $_POST['sign'];
            if ($smscode != $_SESSION['smscode']) {
                echo json_encode(array(
                  'error' => '短信验证码错误',
                  'url' => null,
                ));
                die();
            }
            //1、注册一卡易会员  2、插入数据库，关联一卡易
            $data = [
                "cardId" => $_POST['phone'],
                "password" => $_POST['password'],
                "trueName" => $_POST['gname'],
                "mobile" => $_POST['phone'],
//                "memberGroupName" => "学员卡",
//                "userAccount" => "10000",
                "email" => $_POST['email'],
            ];
//            $response_data = $Cardclient->callHttpPost("Add_Member", $data);
//            if ($response_data["status"]== 0) {
                //注册成功
//                $cardId = $response_data['cardId'];
                $cardId = $data['cardId'];
                $user_obj = new Member();
                //删除现有同id用户
//                $user_obj->deleteUserByObjectId($cardId);
                $_POST['username'] = $_POST['email']?:$_POST['phone'];
                $_POST['user_object_id'] = $cardId;
                $_POST['phone'] = $_POST['phone'];
                $res = $user_obj->create($_POST);
                if ($res['error']) {
                    echo json_encode(array(
                      'error' => $res['error'],
                      'url' => null,
                    ));
                } else {
                    $cart_obj = new Enrolment();
                    $message = $cart_obj->SetUserCart($res['id'], true);
                    $_SESSION['user']['public'] = $res;
                    $url = $_SERVER['HTTP_REFERER'];
                    if ($_POST['redirect']) {
                        $url = $_POST['redirect'];
                    }
                    if ($_POST['email']) {
                        // SEND CONFIRMATION EMAIL
                        try {
                            $SMARTY->assign('DOMAIN', 'http://'.$HTTP_HOST);
                            $COMP = json_encode($CONFIG->company);
                            $SMARTY->assign('COMPANY', json_decode($COMP, true));
                            $SMARTY->assign('name', $res['gname']);
                            $SMARTY->assign('username', $_POST['email']);
                            $SMARTY->assign('password', $_POST['password']);

                            $sql = 'SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id '; //New member
                            if ($res2 = $DBobject->wrappedSql($sql, array(':id' => 9))) {
                                $message = unclean($res2[0]['email_additional_content']);
                                $SMARTY->assign('message', $message);
                            }
                            $buffer = $SMARTY->fetch('email-newmember.tpl');
                            $to = $_SESSION['user']['public']['email'];
                            $from = (string) $CONFIG->company->name;
                            $fromEmail = 'noreply@'.str_replace('www.', '', $HTTP_HOST);
                            $subject = '澳睿跑 (Ready Steady Go Kids) | 新用户注册';
                            $body = $buffer;
                            $mailID = sendMail($to, $from, $fromEmail, $subject, $body, null, $res['id']);
                        } catch (Exception $e) {
                            echo json_encode(array(
                              'error' => null,
                              'emailerror' => $e,
                              'message' => $message,
                            ));
                        }
                    }
                    echo json_encode(array(
                      'error' => null,
                      'url' => $url,
                      'username' => $_SESSION['user']['public']['username'],
                      'message' => $message,
                    ));
                }
//            } else {
//                echo json_encode(array(
//                  'error' => $response_data["message"],
//                  'url' => null,
//                ));
//            }
            die();
        case 'login':
            $user_obj = new Member();
            $userInfo = $user_obj->authenticate($_POST['username'], $_POST['pass']);
            //登陆一卡易会员
            $data = [
                "cardId" => $userInfo["oid"],
                "password" => $_POST['pass'],
            ];
            if (!isset($userInfo["error"])) {
                // 2.发起请求
//                $response = $Cardclient->callHttpPost("MemberLogin", $data);
//                if ($response ["status"] !== 0) {
//                    //登陆失败
//                    echo json_encode(['error' => $response['message'], 'url' => null]);
//                } else {
                    //登陆成功，获取一卡易信息
//                    $res = $Cardclient->getMemberinfo($data['cardId'], true);
                    //更新本地用户数据
//                    $user_obj = new Member();
                    $user = [
                        'user_object_id' => $data['cardId'],
                        'name' => $userInfo['gname'],
                        'email' => $userInfo['email'],
                        'phone' => $userInfo['phone'],
                        'sex' => $userInfo['sex'],
                        'password' => $data['password'],
                    ];
                    $res = $user_obj->create($user, true);
                    //$res = $user_obj->authenticate($_POST['username'], $_POST['pass'], true);
                    if ($res['error']) {
                        //网络错误
                        echo json_encode(['error' => $res['error'], 'url' => null]);
                    } else {
                        $cart_obj = new Enrolment();
                        $message = $cart_obj->SetUserCart($res['id'], true);
                        $_SESSION['user']['public'] = $res;
                        $url = $_SERVER['HTTP_REFERER'];
                        if ($_POST['redirect']) {
                            $url = $_POST['redirect'];
                        }
                        if (empty($_SESSION['address'])) {
                            $addressArr = $user_obj->GetUsersAddresses($res['id']);
                            $_SESSION['address'] = array('S' => $addressArr[0], 'same_address' => true);
                        }
                        $_SESSION['students'] = $user_obj->GetStudentsByUserId($res['id']);

                        $payments = $cart_obj->GetOrderHistoryByUser($res['id']);
                        if (!empty($payments)) {
                            $_SESSION['agreed_tc'] = true;
                        }

                        echo json_encode(['error' => null, 'url' => $url, 'message' => $message]);
                    }
//                }
            } else {
                //错误信息
                echo json_encode(['error' => "用户不存在或密码错误", 'url' => null]);
            }

            die();
        //手机找回密码
        case 'phoneResetPassword':
            $smscode = $_POST['sign'];
            if ($smscode != $_SESSION['smscode']) {
                echo json_encode(array(
                    'error' => '短信验证码错误',
                    'url' => null,
                ));
                die();
            }
            $user_obj = new Member();
            $status = false;
            $phone = $_POST['phone'];
            $password = $_POST['password'];
            $userInfo = $user_obj->retrieveByPhone($phone);
            if (count($userInfo) == 0) {
                //错误信息
                echo json_encode(['error' => '该手机号没有注册,请确认在进行重置密码', 'url' => null]);
                die();
            }
            $temp_str = getPass($userInfo['user_object_id'], $password);
        //            $data = [
        //                'cardId' => $userInfo['user_object_id'],
        //                'password' => $password,
        //            ];
            //一卡易更新密码
        //            $response = $Cardclient->callHttpPost("Update_Member", $data);
        //            if ($response ["status"] !== 0) {
        //                //错误信息
        //                echo json_encode(['error' => $response ["message"], 'url' => null]);
        //                die();
        //            }
            $params = array(
                ':id' => $userInfo['user_id'],
                ':password' => $temp_str,
                ':ip' => $_SERVER['REMOTE_ADDR'],
                ':browser' => $_SERVER['HTTP_USER_AGENT'],
            );
            $sql = 'UPDATE tbl_user SET user_password = :password, user_ip = :ip,user_browser = :browser,user_modified = now() WHERE user_id = :id ';
            if ($DBobject->wrappedSql($sql, $params)) {
                $sql = 'UPDATE tbl_user SET user_token = NULL, user_token_date = NULL WHERE user_id = :id '; //Reset password
                $DBobject->wrappedSql($sql, array('id' => $userInfo['user_id']));
                saveInLog('Edit', 'tbl_user', $userInfo['id']);
                $status = true;
            } else {
                $error = '连接错误。请再试一次！';
            }
            try {
                $res = $user_obj->Authenticate($phone, $password);
                $cart_obj = new Enrolment();
                $message = $cart_obj->SetUserCart($res['id'], true);
                $_SESSION['user']['public'] = $res;
                $url = $_SERVER['HTTP_REFERER'];
                if ($_POST['redirect']) {
                    $url = $_POST['redirect'];
                }
                if (empty($_SESSION['address'])) {
                    $addressArr = $user_obj->GetUsersAddresses($res['id']);
                    $_SESSION['address'] = array('S' => $addressArr[0], 'same_address' => true);
                }
                $_SESSION['students'] = $user_obj->GetStudentsByUserId($res['id']);

                $payments = $cart_obj->GetOrderHistoryByUser($res['id']);
                if (!empty($payments)) {
                    $_SESSION['agreed_tc'] = true;
                }
            } catch (Exception $e) {
            }
            if ($status) {
                echo json_encode(array(
                    'success' => true,
                    'url' => $url,
                ));
                die();
            }
            echo json_encode(array(
                'error' => $error,
                'url' => $url,
            ));
            die();
        case 'resetPassword':
            $user_obj = new Member();
            $res = $user_obj->resetPassword($_POST['email']);
            if ($res['success']) {
                try {
                    // SEND CONFIRMATION EMAIL
                    $sql = 'SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id '; //Reset password
                    if ($res2 = $DBobject->wrappedSql($sql, array(':id' => 10))) {
                        $message = unclean($res2[0]['email_additional_content']);
                        $SMARTY->assign('message', $message);
                    }
                    $SMARTY->assign('name', $res['user_gname']);
                    $SMARTY->assign('token', $res['token']);
                    $SMARTY->assign('email', $_POST['email']);
                    $SMARTY->assign('DOMAIN', 'http://'.$HTTP_HOST);
                    $COMP = json_encode($CONFIG->company);
                    $SMARTY->assign('COMPANY', json_decode($COMP, true));
                    $body = $SMARTY->fetch('email-reset-password.tpl');
                    $to = $_POST['email'];
                    $from = (string)$CONFIG->company->name;
                    $fromEmail = (string)$CONFIG->company->email_from;
                    $subject = '澳睿跑 (Ready Steady Go Kids) | 密码重置';
                    if (sendMail($to, $from, $fromEmail, $subject, $body)) {
                        $success = $res['success'];
                    } else {
                        $error = '发送电子邮件时出错。请稍后再试！';
                    }
                } catch (Exception $e) {
                    $error = $e;
                }
            } else {
                $error = $res['error'];
            }
            echo json_encode(array(
              'error' => $error,
              'success' => $success,
            ));
            die();
        case 'passwordreset':
            $status = false;
            $em = $_POST['email'];
            $tk = $_POST['userToken'];
            $pw = $_POST['pass'];
            $token = getPass($em, $tk);

            // SEND CONFIRMATION EMAIL
            $sql = 'SELECT user_id,IF(user_token_date>=DATE_SUB(NOW( ),INTERVAL 4 HOUR),0,1) AS expired FROM tbl_user WHERE user_token = :token'; //Reset password
            if ($res2 = $DBobject->wrappedSql($sql, array(':token' => $token))) {
                if (empty($res2) || empty($res2[0]) || $res2[0]['expired'] == 1) {
                    $error = '此URL已过期，请刷新页面获取新的密码重置。';
                } else {
                    $user_obj = new Member();
                    $userInfo = $user_obj->retrieveByUsername($em);
                    $temp_str = getPass($userInfo['user_object_id'], $pw);
//                    $data = [
//                        'cardId' => $userInfo['user_object_id'],
//                        'password' => $pw,
//                    ];
                    //一卡易更新密码
//                    $response = $Cardclient->callHttpPost("Update_Member", $data);
//                    if ($response ["status"] !== 0) {
//                        //错误信息
//                        echo json_encode(['error' => $response['message'], 'url' => null]);
//                    }
                    $params = array(
                      ':id' => $res2[0]['user_id'],
                      ':password' => $temp_str,
                      ':ip' => $_SERVER['REMOTE_ADDR'],
                      ':browser' => $_SERVER['HTTP_USER_AGENT'],
                    );
                    $sql = 'UPDATE tbl_user SET user_password = :password, user_ip = :ip,user_browser = :browser,user_modified = now() WHERE user_id = :id ';
                    if ($DBobject->wrappedSql($sql, $params)) {
                        $sql = 'UPDATE tbl_user SET user_token = NULL, user_token_date = NULL WHERE user_id = :id '; //Reset password
                        $DBobject->wrappedSql($sql, array('id' => $res2[0]['user_id']));
                        saveInLog('Edit', 'tbl_user', $res2[0]['id']);
                        $status = true;
                    } else {
                        $error = '连接错误。请再试一次！';
                    }
                    try {
                        $res = $user_obj->Authenticate($em, $pw);
                        $cart_obj = new Enrolment();
                        $message = $cart_obj->SetUserCart($res['id'], true);
                        $_SESSION['user']['public'] = $res;
                        $url = $_SERVER['HTTP_REFERER'];
                        if ($_POST['redirect']) {
                            $url = $_POST['redirect'];
                        }
                        if (empty($_SESSION['address'])) {
                            $addressArr = $user_obj->GetUsersAddresses($res['id']);
                            $_SESSION['address'] = array('S' => $addressArr[0], 'same_address' => true);
                        }
                        $_SESSION['students'] = $user_obj->GetStudentsByUserId($res['id']);

                        $payments = $cart_obj->GetOrderHistoryByUser($res['id']);
                        if (!empty($payments)) {
                            $_SESSION['agreed_tc'] = true;
                        }
                    } catch (Exception $e) {
                    }
                }
            } else {
                $error = '提交出错，请检查您的电子邮件，然后再试一次！';
            }

            if ($status) {
                echo json_encode(array(
                    'error' => false,
                    'success' => true,
                    'url' => $url,
                ));
                die();
            }
            echo json_encode(array(
              'error' => $error,
              'success' => false,
              'url' => $url,
            ));
            die();
        case 'updatePassword':
//            $data = [
//                'cardId' => $_SESSION['user']['public']['oid'],
//                'password' => $_POST['old_password'],
//                'newPassword' => $_POST['password'],
//                'userAccount' => '10000',
//            ];
//            $response_data = $Cardclient->callHttpPost("Update_MemberPassword", $data);
//            if ($response_data['status'] != 0) {
//                $_SESSION['error'] = $response_data['message'];
//                header('Location: '.$_SERVER['HTTP_REFERER'].'#error');
//            } else {
                $user_obj = new Member();
                $data = array_merge($_POST, array(
                    'email' => $_SESSION['user']['public']['email'],
                    'cardId' => $_SESSION['user']['public']['oid'],
                ));
                $res = $user_obj->updatePassword($data);
                if ($res['error']) {
                    $_SESSION['error'] = $res['error'];
                    header('Location: '.$_SERVER['HTTP_REFERER'].'#error');
                } else {
                    $_SESSION['notice'] = $res['success'];
                    header('Location: '.$_SERVER['HTTP_REFERER'].'#notice');
                }
//            }
            die();
        case 'updateDetails':
            $user_obj = new Member();
            $data = array_merge($_POST, array('user_id' => $_SESSION['user']['public']['id']));
            $promo = 0;
            $data['user_want_promo'] = $promo;
            $res = $user_obj->UpdateDetails($data);
            if ($user_obj->InsertNewAddress(array_merge(
                array(
                  'address_user_id' => $_SESSION['user']['public']['id'],
                  'address_name' => $_POST['user_gname'],
                  'address_surname' => $_POST['user_surname'], ),
                $_POST
            ))) {
                $addressArr = $user_obj->GetUsersAddresses($_SESSION['user']['public']['id']);
                $_SESSION['address'] = array('S' => $addressArr[0], 'same_address' => true);
            }

            if ($res['error']) {
                $_SESSION['error'] = $res['error'];
                header('Location: '.$_SERVER['HTTP_REFERER'].'#contact');
            } else {
                //更新一卡易会员信息
                $region = new Region();
                $data = [
                    'cardId' => $_SESSION['user']['public']['oid'],
                    'sex' => $_POST['sex'],
                    'trueName' => $_POST['user_gname'],
                    'email' => $_POST['user_email'],
                    'address' => $_POST['address_line1'],
                    'provinceId' => $region->getProvinceId($_POST['address_state']),
                    'cityId' => $region->getCityId($_POST['address_suburb']),
                    'countyId' => $region->getCountyId($_POST['address_country']),
                    'postCode' => $_POST['address_postcode'],
                ];
                $response_data = $Cardclient->callHttpPost("Update_Member", $data);
                if ($response_data["status"] != 0) {
                    $_SESSION['error'] = $response_data['message'];
                    header('Location: '.$_SERVER['HTTP_REFERER'].'#contact');
                } else {
                    $_SESSION['user']['public']['gname'] = $_POST['user_gname'];
                    $_SESSION['user']['public']['sex'] = $_POST['user_sex'];
                    $_SESSION['user']['public']['email'] = $_POST['user_email'];
                    $_SESSION['user']['public']['user_want_promo'] = $promo;
                    $_SESSION['notice'] = $res['success'];
                    header('Location: '.$_SERVER['HTTP_REFERER'].'#contact');
                }
            }
            die();
        case 'updateStudentDetails':
            $user_obj = new Member();
            if ($res = $user_obj->editStudent($_POST['student'])) {
                $success = "您孩子的信息已经更新。";
                $error = null;
                $_SESSION['students'] = $user_obj->GetStudentsByUserId($_SESSION['user']['public']['id']);
            } else {
                $error = "未知错误导致更新失败。请联系我们。";
                $success = null;
            }

            echo json_encode([
                'error' => $error,
                'success' => $success,
            ]);
            die();
    }
}
$redirect = $_SERVER['HTTP_REFERER'];
if ($_GET['logout']) {
    unset($_SESSION['user']['public']);
    unset($_SESSION['address']);
    unset($_SESSION['comments']);
    unset($_SESSION['students']);
    unset($_SESSION['agreed_tc']);
    session_regenerate_id();
    if (empty($redirect) || preg_match('/process/', $_SERVER['HTTP_REFERER'])) {
        $redirect = '/';
    }
    header('Location: '.$redirect);
    die();
}
$_SESSION['error'] = 'Your session has expired.';
if (empty($redirect) || preg_match('/process/', $_SERVER['HTTP_REFERER'])) {
    $redirect = '/';
}
header('Location: '.$redirect.'#error');
die();
